package com.weather.modules.job.task;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.weather.common.config.RabbitConfig;
import com.weather.common.constants.UrlConstants;
import com.weather.common.utils.JsonUtils;
import com.weather.common.vo.City;
import com.weather.common.vo.WeatherVo;
import com.weather.modules.city.service.CityClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;


public class WeatherTask extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final long TIME_OUT = 1800L; // 1800s

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CityClient cityClient;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private AmqpTemplate rabbitTemplate;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("Weather Data Sync Job. Start！");
        // 获取城市ID列表
        List<City> cityList = null;
        try {
            cityList = cityClient.listCity();
        } catch (Exception e) {
            logger.error("Exception!", e);
        }
        // 遍历城市ID获取天气
        for(int i = 0,length = cityList.size(); i < length; i++){
            String cityId = cityList.get(i).getCityId();
            logger.info("Weather Data Sync Job, cityId:" + cityId);
            this.syncDateByCityId(cityId);
        }
        logger.info("Weather Data Sync Job. End！");
    }

    /**
     * 根据城市id获取城市天气信息
     * @param cityId
     */
    public void syncDateByCityId(final String cityId) {
        String key = UrlConstants.WEATHER_URI + "citykey=" + cityId;
        String strBody = null;

        // 调用服务接口来获取 restTemplate 是服务调用不是 redis
        ResponseEntity<String> respString = this.restTemplate.getForEntity(key, String.class);
        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
            JSONObject json_test = JSONObject.parseObject(strBody);
            Object weatherdata = json_test.get("data");
            WeatherVo weather = JsonUtils.jsonToPojo(weatherdata +"", WeatherVo.class);
            // 数据写入缓存
            /*this.redisTemplate.opsForValue().set(cityId, strBody, TIME_OUT, TimeUnit.SECONDS);*/
            this.redisTemplate.opsForValue().set(cityId, strBody);
            weather.setCityId(cityId);
            /**
            Map<String,String> mqdata = Collections.synchronizedMap(new HashMap<String,String>());
            mqdata.put(cityId,strBody);
            */
            Gson gson = new Gson();
            String mqBody = gson.toJson(weather);
            this.rabbitTemplate.convertAndSend(RabbitConfig.TOPICEXCHANGE,RabbitConfig.ROUTING_WEATHERKEY,mqBody);
        }

    }
}
